/*
 * ============================================================================
 *
 *       Filename:  buffer.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/23/2018 07:00:06 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>

#include "main.h"

int balloc(buffer_t *ptr, size_t capacity)
{
	memset(ptr, 0, sizeof(buffer_t));
	ptr->array    = ss_malloc(capacity);
	ptr->capacity = capacity;
	return capacity;
}

int brealloc(buffer_t *ptr, size_t len, size_t capacity)
{
	if (ptr == NULL)
		return -1;
	size_t real_capacity = max(len, capacity);
	if (ptr->capacity < real_capacity) {
		ptr->array    = ss_realloc(ptr->array, real_capacity);
		ptr->capacity = real_capacity;
	}
	return real_capacity;
}

buffer_t *bconcat_str(buffer_t *buf, char *data)
{
	int len = strlen(data);
	brealloc(buf, buf->len + len, buf->capacity);
	memcpy(buf->array + buf->len, data, len);
	buf->len += len;
	return buf;
}

buffer_t *bconcat(buffer_t *buf, char *data, int len)
{
	brealloc(buf, buf->len + len, buf->capacity);
	memcpy(buf->array + buf->len, data, len);
	buf->len += len;
	return buf;
}

char *buf_offset(buffer_t *buf)
{
	return buf->array + buf->len;
}

buffer_t *bconcat_pre(buffer_t *buf, int len)
{
	brealloc(buf, buf->len + len, buf->capacity);
	return buf;
}

buffer_t *bconcat_suf(buffer_t *buf, int len)
{
	buf->len += len;
	return buf;
}

void breset(buffer_t *ptr)
{
	ptr->len = 0;
	ptr->idx = 0;
}

void bshrink(buffer_t *ptr, int len)
{
	ptr->len -= len;
	ptr->idx = len;
	memmove(ptr->array, ptr->array + ptr->idx, ptr->len);
	ptr->idx = 0;
}

int bufempty(buffer_t *ptr)
{
	return !ptr->len;
}

void bfree(buffer_t *ptr)
{
	if (ptr == NULL)
		return;
	ptr->idx      = 0;
	ptr->len      = 0;
	ptr->capacity = 0;
	if (ptr->array != NULL) {
		ss_free(ptr->array);
	}
}
